<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('分享标题')" prop="shareTitle">
            <el-input v-model="form.shareTitle" :placeholder="$t('分享标题')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('过期时间')" prop="aging">
            <el-date-picker
              v-model="form.aging"
              type="datetime"
              align="left"
              :placeholder="$t('为空时不过期!')"
              clearable
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('查看人能否编辑')" prop="edit">
            <el-radio v-model="form.edit" label="Y">{{ $t('是') }}</el-radio>
            <el-radio v-model="form.edit" label="N">{{ $t('否') }}</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('查看人能否下载')" prop="download">
            <el-radio v-model="form.download" label="Y">{{ $t('是') }}</el-radio>
            <el-radio v-model="form.download" label="N">{{ $t('否') }}</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.id" :label="$t('分享人')" prop="userId">
            <UserSelect v-model="form.userId" :disabled="true" :placeholder="$t('分享人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.id" :label="$t('分享链接')" prop="url">
            <el-input v-model="form.url" disabled :placeholder="$t('分享链接')" show-word-limit maxlength="1000">
              <template slot="append">
                <el-tooltip class="item" effect="dark" :content="$t('跳转连接')" placement="top-start">
                  <router-link
                    target="_blank"
                    :to="{ path:'/SysShareHome?id=' + form.id, query:{ id: form.id } }"
                    class="link_a el-icon-link"
                  />
                </el-tooltip>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="area-header">
        <span class="area-header-title">{{ $t('分享列表') }}</span>
      </div>
      <el-table :data="form.fileList" border style="overflow: auto; height: 400px;">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件名称')" align="left" prop="fileName">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="onlinePreviewOnlineEdit('view', scope.row.fileId)">{{ $t(scope.row.fileName) }}</el-link>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件大小')" align="center" prop="sizes" width="150">
          <template slot-scope="scope">
            <span>{{ calculateFileSize(scope.row.sizes) }} {{ calculateFileSize(scope.row.size) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('上传时间')" align="center" prop="updateTime" width="150" />
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteSubHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
            <el-button
              v-if="fromRecordPageFileId === undefined || fromRecordPageFileId === null || fromRecordPageFileId === ''"
              size="small"
              type="text"
              icon="el-icon-view"
              @click="fileOrDirRecord(scope.row)"
            >{{ $t('日志') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!--保存 取消按钮-->
    <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 15px;">
      <div style="display: inline-block; margin-left: 10px;">
        <el-button @click="cancel">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('分享') }}</el-button>
      </div>
    </div>

    <!--操作历史页面-->
    <el-dialog :title="title" :visible.sync="fileOrDirRecordLoading" width="80%" :close-on-click-modal="false" :destroy-on-close="true" append-to-body>
      <fileOperationRecord ref="fileOperationRecord" />
    </el-dialog>

    <!-- 分享贴图 -->
    <el-dialog :title="$t('分享详情')" :visible.sync="shareUrlMsgOpen" style="height: 520px;" width="520px" :close-on-click-modal="false" :destroy-on-close="true" append-to-body>
      <sysShareFileUrlMsg ref="sysShareFileUrlMsg" />
    </el-dialog>

    <!-- 附件预览 -->
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import { saveSysShareFiles, getSysShareFiles } from '@/api/file/share/sysShareFiles.js'
import fileOperationRecord from '@/views/file/document/library/fileOperationRecord.vue'
import sysShareFileUrlMsg from '@/views/file/share/sysShareFileUrlMsg.vue'
export default {
  components: {
    fileOperationRecord,
    sysShareFileUrlMsg
  },
  // 如果存在ID, 就是来自操作日志页面, 否则走正常加载
  props: {
    fromRecordPageFileId: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      // 表单参数
      form: {},
      title: '',
      // 遮罩层
      loading: false,
      fileOrDirRecordLoading: false,
      shareUrlMsgOpen: false,
      // 表单校验
      rules: {
        shareTitle: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        url: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        userId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        edit: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        download: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [
          {
            text: this.$t('一天'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('三天'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('一星期'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('一个月'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = false
      if (data != null && data.id !== undefined) {
        this.loading = true
        getSysShareFiles(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.form.fileList = []
        if (data) {
          data.forEach(item => {
            const row = {
              fileId: item.id,
              fileName: item.name,
              updateTime: item.updateTime,
              sizes: item.sizes,
              size: item.size
            }
            this.form.fileList.push(row)
          })
        }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        url: window.location.protocol + '//' + window.location.host + '/SysShareHome?id=',
        edit: 'N',
        download: 'Y',
        userId: undefined,
        createBy: undefined,
        createTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.shareFilesFormOpen = false
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.cancel()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        var flag = false
        if (this.form.fileList !== undefined && this.form.fileList.length > 0) {
          flag = true
        } else {
          this.msgError(this.$t('没有发现要分享的文件'))
        }
        if (valid && flag) {
          this.loading = true
          saveSysShareFiles(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.shareUrlMsgOpen = true
              this.$nextTick(() => {
                this.$refs.sysShareFileUrlMsg.init(response.data)
                this.closeForm()
              })
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 计算文件大小  换算单位
    calculateFileSize(size) {
      size = parseInt(size)
      if (size > 0 && size < 1048576) {
        return (size / 1024).toFixed(2) + ' KB'
      } else if (size > 1048576) {
        return (size / 1024 / 1024).toFixed(2) + ' MB'
      } else {
        return ''
      }
    },
    // 预览附件
    onlinePreviewOnlineEdit(type, id) {
      this.$refs.OnlinePreview.onlinePreviewFile(id, type)
    },
    // 删除子表附件
    deleteSubHandle(row) {
      console.log(row)
      var that = this
      this.$confirm(that.$t('是否确认删除?'), that.$t('警告'), {
        confirmButtonText: that.$t('确定'),
        cancelButtonText: that.$t('取消'),
        type: 'warning'
      }).then(function() {
        if (that.form.fileList) {
          that.form.fileList.forEach((item, index) => {
            if (item.fileId === row.fileId) {
              that.form.fileList.splice(index, 1)
            }
          })
        }
      })
    },
    // 查看操作历史
    fileOrDirRecord(row) {
      this.fileOrDirRecordLoading = true
      this.title = this.$t('操作历史')
      this.$nextTick(() => {
        this.$refs.fileOperationRecord.fileDirId = row.fileId
        this.$refs.fileOperationRecord.init()
      })
    }
  }

}
</script>
<style scoped>
.el-table__body-wrapper {
  height: 400px;
  overflow: auto;
}
</style>
